/**
 * 简谱打谱软件 - 导入功能模块
 */

// 导入XML格式的项目
function importFromXML(xmlContent) {
  try {
    const parser = new DOMParser();
    const xmlDoc = parser.parseFromString(xmlContent, 'text/xml');
    
    // 解析元数据
    const title = xmlDoc.querySelector('title')?.textContent || '';
    const composer = xmlDoc.querySelector('composer')?.textContent || '';
    const lyricist = xmlDoc.querySelector('lyricist')?.textContent || '';
    const keySignature = xmlDoc.querySelector('keySignature')?.textContent || 'C';
    const timeSignature = xmlDoc.querySelector('timeSignature')?.textContent || '4/4';
    const tempo = xmlDoc.querySelector('tempo')?.textContent || 120;
    
    // 解析小节
    const barNodes = xmlDoc.querySelectorAll('bar');
    const bars = Array.from(barNodes).map(barNode => {
      const noteNodes = barNode.querySelectorAll('note');
      return Array.from(noteNodes).map(noteNode => noteNode.textContent);
    });
    
    // 解析歌词
    const lyricNodes = xmlDoc.querySelectorAll('lyric');
    const lyrics = Array.from(lyricNodes).map(lyricNode => lyricNode.textContent);
    
    // 更新表单和状态
    document.getElementById('song-title').value = title;
    document.getElementById('composer').value = composer;
    document.getElementById('lyricist').value = lyricist;
    document.getElementById('key-signature').value = keySignature;
    document.getElementById('time-signature').value = timeSignature;
    document.getElementById('tempo').value = tempo;
    document.getElementById('tempo-value').textContent = `${tempo} BPM`;
    
    appState.bars = bars;
    appState.lyrics = lyrics;
    
    // 更新预览
    updatePreview();
    
    showNotification('XML文件已导入！', 'success');
  } catch (error) {
    console.error('导入XML失败:', error);
    showNotification('导入XML失败，请检查文件格式！', 'error');
  }
}

// 导入JSON格式的项目
function importFromJSON(jsonContent) {
  try {
    const projectData = JSON.parse(jsonContent);
    
    // 更新表单和状态
    document.getElementById('song-title').value = projectData.metadata.title || '';
    document.getElementById('composer').value = projectData.metadata.composer || '';
    document.getElementById('lyricist').value = projectData.metadata.lyricist || '';
    document.getElementById('key-signature').value = projectData.metadata.keySignature || 'C';
    document.getElementById('time-signature').value = projectData.metadata.timeSignature || '4/4';
    document.getElementById('tempo').value = projectData.metadata.tempo || 120;
    document.getElementById('tempo-value').textContent = `${projectData.metadata.tempo || 120} BPM`;
    
    appState.bars = projectData.bars || [];
    appState.lyrics = projectData.lyrics || [];
    
    // 更新预览
    updatePreview();
    
    showNotification('JSON文件已导入！', 'success');
  } catch (error) {
    console.error('导入JSON失败:', error);
    showNotification('导入JSON失败，请检查文件格式！', 'error');
  }
}

// 导入文本格式的项目
function importFromText(textContent) {
  try {
    // 假设文本格式为：
    // 第一行：标题
    // 第二行：作曲
    // 第三行：作词
    // 第四行：调号
    // 第五行：拍号
    // 第六行：速度
    // 空行后：小节（每行一个小节，音符用空格分隔）
    // 再空行后：歌词（每行一句）
    
    const lines = textContent.split('\n');
    
    // 解析元数据
    document.getElementById('song-title').value = lines[0] || '';
    document.getElementById('composer').value = lines[1] || '';
    document.getElementById('lyricist').value = lines[2] || '';
    document.getElementById('key-signature').value = lines[3] || 'C';
    document.getElementById('time-signature').value = lines[4] || '4/4';
    document.getElementById('tempo').value = lines[5] || 120;
    document.getElementById('tempo-value').textContent = `${lines[5] || 120} BPM`;
    
    // 找到小节开始的位置
    let barsStartIndex = 6;
    while (barsStartIndex < lines.length && lines[barsStartIndex].trim() === '') {
      barsStartIndex++;
    }
    
    // 找到小节结束的位置
    let barsEndIndex = barsStartIndex;
    while (barsEndIndex < lines.length && lines[barsEndIndex].trim() !== '') {
      barsEndIndex++;
    }
    
    // 解析小节
    const bars = [];
    for (let i = barsStartIndex; i < barsEndIndex; i++) {
      if (lines[i].trim() !== '') {
        bars.push(lines[i].trim().split(' '));
      }
    }
    
    // 找到歌词开始的位置
    let lyricsStartIndex = barsEndIndex;
    while (lyricsStartIndex < lines.length && lines[lyricsStartIndex].trim() === '') {
      lyricsStartIndex++;
    }
    
    // 解析歌词
    const lyrics = [];
    for (let i = lyricsStartIndex; i < lines.length; i++) {
      if (lines[i].trim() !== '') {
        lyrics.push(lines[i].trim());
      }
    }
    
    // 更新状态
    appState.bars = bars;
    appState.lyrics = lyrics;
    
    // 更新预览
    updatePreview();
    
    showNotification('文本文件已导入！', 'success');
  } catch (error) {
    console.error('导入文本失败:', error);
    showNotification('导入文本失败，请检查文件格式！', 'error');
  }
}
    